package password.hb.com.password.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import password.hb.com.password.R;
import password.hb.com.password.entity.Password;
import password.hb.com.password.factory.ThreadFactory;
import password.hb.com.password.model.PasswordModel;

/**
 * Created by A on 2016/12/6.
 */

public class PasswordAdapter extends BaseAdapter{

    private Context context;
    private List<Password> passwordList;

    public PasswordAdapter(Context context,List<Password> passwordList){
        this.context = context;
        this.passwordList = new ArrayList<>();
        this.passwordList.addAll(passwordList);
    }

    @Override
    public int getCount() {
        return passwordList.size();
    }

    @Override
    public Object getItem(int position) {
        return passwordList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void remove(int position){
        PasswordModel.getInstance().delete(this.passwordList.get(position));
        passwordList.remove(position);
        this.notifyDataSetChanged();
    }

    public List<Password> getPasswordList(){
        return this.passwordList;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder ;
        if(convertView == null){
            convertView = View.inflate(context, R.layout.item_passwordlist,null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }
        holder.freshUI(passwordList.get(position));
        return convertView;
    }

    class ViewHolder {
        private ImageView pwdImg;
        private TextView pwdAppName;
        private TextView pwdTag;

        public ViewHolder(View convertView){
            pwdImg = (ImageView) convertView.findViewById(R.id.password_img);
            pwdAppName = (TextView) convertView.findViewById(R.id.password_app_name);
            pwdTag = (TextView) convertView.findViewById(R.id.password_app_tag);
        }

        public void freshUI(Password password){
            pwdImg.setImageResource(password.getAppImageId());
            pwdAppName.setText(password.getUserName());
            pwdTag.setText(password.getTag());
        }
    }

}
